package com.example.viewdemo.serviceTest

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.viewdemo.databinding.ActivityMainServiceTestBinding

class MainActivityServiceTest : AppCompatActivity(), View.OnClickListener {
    private lateinit var binding: ActivityMainServiceTestBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding= ActivityMainServiceTestBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.stopServiceBtn.setOnClickListener(this)
        binding.startServiceBtn.setOnClickListener(this)
        binding.bindServiceBtn.setOnClickListener(this)
        binding.unbindServiceBtn.setOnClickListener(this)
    }

    lateinit var downloadBinder: MyService.DownloadBinder
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            downloadBinder = service as MyService.DownloadBinder
            downloadBinder.startDownload()
            downloadBinder.getProgress()
        }
        override fun onServiceDisconnected(name: ComponentName) {
        }
    }
    override fun onClick(v: View?) {
       when(v){
           binding.startServiceBtn->{
               val intent = Intent(this, MyService::class.java)
               startService(intent) // 启动Service
           }
           binding.stopServiceBtn->{
               val intent = Intent(this, MyService::class.java)
               stopService(intent) // 停止Service
           }
           binding.bindServiceBtn->{
               val intent = Intent(this, MyService::class.java)
               bindService(intent, connection, Context.BIND_AUTO_CREATE) // 绑定Service
           }
           binding.unbindServiceBtn->{
               unbindService(connection) // 解绑Service
           }
       }
    }
}